<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="85px">
      <el-form-item label="配置名称" prop="configName">
        <el-input
          v-model="queryParams.configName"
          placeholder="请输入配置名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="equipmentTypeId">
        <el-select v-model="queryParams.equipmentTypeId" placeholder="请选择设备类型" clearable size="small">
          <el-option
            v-for="item in equipmentTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="配置类别" prop="configCategory">
        <el-select v-model="queryParams.configCategory" placeholder="请选择配置类别" clearable size="small">
          <el-option value="0" label="标准配置" />
          <el-option value="1" label="自定义配置" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="configStatus">
        <el-select v-model="queryParams.configStatus" placeholder="请选择状态" clearable size="small">
          <el-option value="0" label="停用" />
          <el-option value="1" label="正常" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sb:maintenance-config:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sb:maintenance-config:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleBatchDelete"
          v-hasPermi="['sb:maintenance-config:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sb:maintenance-config:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="configList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="配置编码" align="center" prop="configCode" />
      <el-table-column label="配置名称" align="center" prop="configName" :show-overflow-tooltip="true" />
      <el-table-column label="设备类型" align="center" prop="equipmentTypeName" :show-overflow-tooltip="true" />
      <el-table-column label="配置类别" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.configCategory === '0'" type="success">标准</el-tag>
          <el-tag v-else type="warning">自定义</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="保养项数量" align="center">
        <template slot-scope="scope">
          <el-tag type="info">{{ scope.row.maintenanceItems ? scope.row.maintenanceItems.length : 0 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.configStatus"
            :active-value="'1'"
            :inactive-value="'0'"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewItems(scope.row)"
          >查看保养项</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sb:maintenance-config:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sb:maintenance-config:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改保养配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="880px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="配置名称" prop="configName">
                  <el-input v-model="form.configName" placeholder="请输入配置名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="配置编码" prop="configCode">
                  <el-input v-model="form.configCode" placeholder="自动生成，可手动修改" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="设备类型" prop="equipmentTypeId">
                  <el-select v-model="form.equipmentTypeId" placeholder="请选择设备类型" @change="handleEquipmentTypeChange" style="width: 100%;">
                    <el-option
                      v-for="item in equipmentTypeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="配置类别" prop="configCategory">
                  <el-radio-group v-model="form.configCategory">
                    <el-radio label="0">标准配置</el-radio>
                    <el-radio label="1">自定义配置</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="状态" prop="configStatus" v-if="!form.configId">
                  <el-radio-group v-model="form.configStatus">
                    <el-radio label="0">停用</el-radio>
                    <el-radio label="1">正常</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="保养项管理" name="items">
            <el-alert
              title="请先保存配置基本信息，再添加保养项"
              type="warning"
              v-if="!form.configId"
              show-icon
              :closable="false"
            ></el-alert>
            
            <div v-if="form.configId">
              <el-row style="margin-bottom: 10px;">
                <el-button 
                  type="primary" 
                  size="mini" 
                  icon="el-icon-plus" 
                  @click="handleAddItem" 
                  :disabled="!form.configId">添加保养项</el-button>
              </el-row>
              
              <el-table :data="form.maintenanceItems || []" border style="width: 100%">
                <el-table-column label="序号" type="index" width="50" align="center" />
                <el-table-column label="保养项名称" prop="itemName" min-width="200" :show-overflow-tooltip="true" />
                <el-table-column label="保养操作" prop="itemMethod" min-width="300" :show-overflow-tooltip="true" />
                <el-table-column label="操作" align="center" width="150">
                  <template slot-scope="scope">
                    <el-button 
                      size="mini" 
                      type="text" 
                      icon="el-icon-edit" 
                      @click="handleEditItem(scope.$index, scope.row)">编辑</el-button>
                    <el-button 
                      size="mini" 
                      type="text" 
                      icon="el-icon-delete" 
                      @click="handleDeleteItem(scope.$index, scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>

    <!-- 保养项对话框 -->
    <el-dialog :title="itemTitle" :visible.sync="itemDialogVisible" width="580px" append-to-body>
      <el-form ref="itemForm" :model="itemForm" :rules="itemRules" label-width="100px">
        <el-form-item label="保养项名称" prop="itemName">
          <el-input v-model="itemForm.itemName" placeholder="请输入保养项名称" />
        </el-form-item>
        <el-form-item label="保养操作" prop="itemMethod">
          <el-input v-model="itemForm.itemMethod" type="textarea" placeholder="请输入保养操作" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitItemForm">确 定</el-button>
        <el-button @click="cancelItemForm">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 查看保养项对话框 -->
    <el-dialog title="查看保养项" :visible.sync="viewItemsDialogVisible" width="600px" append-to-body>
      <el-table :data="currentItems" border style="width: 100%">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="保养项名称" prop="itemName" min-width="200" :show-overflow-tooltip="true" />
        <el-table-column label="保养操作" prop="itemMethod" min-width="300" :show-overflow-tooltip="true" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewItemsDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEquipmentType } from "@/api/sb/equipmentTypes";
import { 
  listMaintenanceConfig, 
  getMaintenanceConfig, 
  addMaintenanceConfig, 
  updateMaintenanceConfig, 
  delMaintenanceConfig
} from "@/api/sb/maintenanceConfig";
import {
  listMaintenanceItem,
  getMaintenanceItem,
  addMaintenanceItem,
  updateMaintenanceItem,
  delMaintenanceItem,
  getItemsByConfigId
} from "@/api/sb/maintenanceItem";

export default {
  name: "MaintenanceConfig",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 保养配置表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前选中的标签页
      activeTab: 'basic',
      // 设备类型选项
      equipmentTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        configName: null,
        equipmentTypeId: null,
        configCategory: null,
        configStatus: null
      },
      // 表单参数
      form: {
        configId: null,
        configCode: null,
        configName: null,
        equipmentTypeId: null,
        equipmentTypeName: null,
        configCategory: "0",
        configStatus: "1",
        remark: null,
        maintenanceItems: []
      },
      // 表单校验
      rules: {
        configName: [
          { required: true, message: "配置名称不能为空", trigger: "blur" }
        ],
        equipmentTypeId: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ]
      },
      // 保养项相关
      itemDialogVisible: false,
      itemTitle: "",
      itemIndex: -1,
      itemForm: {
        itemId: null,
        configId: null,
        itemName: null,
        itemMethod: null
      },
      itemRules: {
        itemName: [
          { required: true, message: "保养项名称不能为空", trigger: "blur" }
        ],
        itemMethod: [
          { required: true, message: "保养操作不能为空", trigger: "blur" }
        ]
      },
      // 查看保养项
      viewItemsDialogVisible: false,
      currentItems: []
    };
  },
  created() {
    this.getList();
    this.getEquipmentTypeList();
  },
  methods: {
    /** 查询保养配置列表 */
    getList() {
      this.loading = true;
      listMaintenanceConfig(this.queryParams).then(response => {
        this.configList = response.rows || [];
        this.total = parseInt(response.total) || 0;
        
        // 加载每个配置下的保养项
        this.configList.forEach(config => {
          this.loadMaintenanceItems(config);
        });
        
        this.loading = false;
      }).catch(error => {
        console.error("获取保养配置列表失败", error);
        this.configList = [];
        this.total = 0;
        this.loading = false;
      });
    },
    /** 查询设备类型列表 */
    getEquipmentTypeList() {
      listEquipmentType().then(response => {
        const typeList = response.rows || response.data || [];
        this.equipmentTypeOptions = typeList.map(item => {
          return {
            value: item.typeId,
            label: item.typeName
          };
        });
      }).catch(error => {
        console.error("获取设备类型列表失败", error);
        this.equipmentTypeOptions = [];
      });
    },
    /** 加载保养项 */
    loadMaintenanceItems(config) {
      if (!config.configId) return;
      
      getItemsByConfigId(config.configId).then(response => {
        this.$set(config, 'maintenanceItems', response.rows || []);
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        configId: null,
        configCode: null,
        configName: null,
        equipmentTypeId: null,
        equipmentTypeName: null,
        configCategory: "0",
        configStatus: "1",
        remark: null,
        maintenanceItems: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.configId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加保养配置";
      this.activeTab = 'basic';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const configId = row.configId || this.ids[0]
      getMaintenanceConfig(configId).then(response => {
        this.form = response.data;
        // 加载保养项
        getItemsByConfigId(configId).then(itemResponse => {
          this.form.maintenanceItems = itemResponse.rows || [];
        });
        this.open = true;
        this.title = "修改保养配置";
        this.activeTab = 'basic';
      });
    },
    /** 设备类型选择变更 */
    handleEquipmentTypeChange(value) {
      this.equipmentTypeOptions.forEach(option => {
        if (option.value === value) {
          this.form.equipmentTypeName = option.label;
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const formData = {
            configId: this.form.configId,
            configCode: this.form.configCode,
            configName: this.form.configName,
            equipmentTypeId: this.form.equipmentTypeId,
            equipmentTypeName: this.form.equipmentTypeName,
            configCategory: this.form.configCategory || "0", // 确保有默认值
            configStatus: this.form.configStatus || "0", // 确保有默认值
            remark: this.form.remark
          };
          
          if (formData.configId != null) {
            updateMaintenanceConfig(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("修改保养配置失败", error);
            });
          } else {
            addMaintenanceConfig(formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("新增保养配置失败", error);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const configIds = row.configId || this.ids;
      this.$modal.confirm('是否确认删除保养配置编号为"' + configIds + '"的数据项？').then(() => {
        return delMaintenanceConfig(configIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    
    /** 批量删除按钮操作 */
    handleBatchDelete() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要删除的数据");
        return;
      }
      this.$modal.confirm('确认删除选中的' + this.ids.length + '条数据吗？').then(() => {
        return delMaintenanceConfig(this.ids.join(','));
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('ldzl-sb/maintenance/config/export', {
        ...this.queryParams
      }, `maintenance_config_${new Date().getTime()}.xlsx`);
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.configStatus === "0" ? "停用" : "启用";
      this.$modal.confirm('确认要"' + text + '""' + row.configName + '"吗？').then(function() {
        return updateMaintenanceConfig({
          configId: row.configId,
          configStatus: row.configStatus
        });
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(() => {
        row.configStatus = row.configStatus === "0" ? "1" : "0";
      });
    },
    /** 查看保养项 */
    handleViewItems(row) {
      if (row.maintenanceItems && row.maintenanceItems.length > 0) {
        this.currentItems = JSON.parse(JSON.stringify(row.maintenanceItems));
      } else {
        getItemsByConfigId(row.configId).then(response => {
          this.currentItems = response.rows || [];
        }).catch(error => {
          console.error('获取保养项失败:', error);
          this.currentItems = [];
        });
      }
      this.viewItemsDialogVisible = true;
    },
    /** 添加保养项 */
    handleAddItem() {
      this.itemForm = {
        itemId: null,
        configId: this.form.configId,
        itemName: null,
        itemMethod: null
      };
      this.itemTitle = "添加保养项";
      this.itemIndex = -1;
      this.itemDialogVisible = true;
    },
    /** 编辑保养项 */
    handleEditItem(index, row) {
      this.itemForm = JSON.parse(JSON.stringify(row));
      this.itemTitle = "编辑保养项";
      this.itemIndex = index;
      this.itemDialogVisible = true;
    },
    /** 删除保养项 */
    handleDeleteItem(index, row) {
      if (row.itemId) {
        // 已有ID的项，调用接口删除
        this.$modal.confirm('确认删除该保养项吗？').then(() => {
          return delMaintenanceItem(row.itemId);
        }).then(() => {
          this.form.maintenanceItems.splice(index, 1);
          this.$modal.msgSuccess("删除成功");
        }).catch((error) => {
          console.error("删除保养项失败", error);
        });
      } else {
        // 未保存的项，直接删除
        this.form.maintenanceItems.splice(index, 1);
      }
    },
    /** 保养项表单提交 */
    submitItemForm() {
      this.$refs.itemForm.validate(valid => {
        if (valid) {
          // 确保所有字段都有值
          const itemData = {
            ...this.itemForm
          };
          
          if (this.itemForm.itemId) {
            // 更新已有保养项
            updateMaintenanceItem(itemData).then(response => {
              if (this.itemIndex > -1) {
                this.form.maintenanceItems[this.itemIndex] = JSON.parse(JSON.stringify(itemData));
              }
              this.$modal.msgSuccess("修改成功");
              this.itemDialogVisible = false;
            });
          } else {
            // 添加新保养项
            addMaintenanceItem(itemData).then(response => {
              itemData.itemId = response.data.itemId;
              if (!this.form.maintenanceItems) {
                this.$set(this.form, 'maintenanceItems', []);
              }
              this.form.maintenanceItems.push(JSON.parse(JSON.stringify(itemData)));
              this.$modal.msgSuccess("添加成功");
              this.itemDialogVisible = false;
            });
          }
        }
      });
    },
    /** 取消保养项表单 */
    cancelItemForm() {
      this.itemDialogVisible = false;
      this.resetForm("itemForm");
    }
  }
};
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
</style> 